package com.zhentao.ws;

import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.Map;

/**
 * 学生端文本WS处理器
 * 连接示例：/ws/chat?userId=123&userType=1
 */
public class ChatWebSocketHandler extends TextWebSocketHandler {

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        Map<String, String> params = Utils.parseQuery(session.getUri());
        Integer userType = Integer.valueOf(params.getOrDefault("userType", "0"));
        Long userId = Long.valueOf(params.getOrDefault("userId", "0"));
        String key = WebSocketSessionManager.buildKey(userType, userId);
        WebSocketSessionManager.put(key, session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        session.sendMessage(new TextMessage("ACK:" + message.getPayload()));
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        Map<String, String> params = Utils.parseQuery(session.getUri());
        Integer userType = Integer.valueOf(params.getOrDefault("userType", "0"));
        Long userId = Long.valueOf(params.getOrDefault("userId", "0"));
        String key = WebSocketSessionManager.buildKey(userType, userId);
        WebSocketSessionManager.remove(key);
    }

    static class Utils {
        static Map<String, String> parseQuery(java.net.URI uri) {
            java.util.HashMap<String, String> map = new java.util.HashMap<>();
            String q = uri.getQuery();
            if (q == null || q.isEmpty()) return map;
            for (String part : q.split("&")) {
                String[] kv = part.split("=", 2);
                if (kv.length == 2) map.put(kv[0], kv[1]);
            }
            return map;
        }
    }
}